<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery">
            <el-icon style="margin-right: 5px;"><Search /></el-icon>
            搜索
        </el-button>
        <el-button size="mini" @click="resetQuery">
            <el-icon style="margin-right: 5px;"><Refresh /></el-icon>
            重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
        >
        <el-icon style="margin-right: 5px;"><Plus /></el-icon>
        新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >
        <el-icon style="margin-right: 5px;"><Delete /></el-icon>
        删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="preregisterList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="registerId" width="80" />
      <el-table-column label="申请人" align="center" prop="mainRenter.name" />
      <el-table-column label="房客类型" align="center" prop="mainRenter.renterType" width="100">
        <template #default="{ row }">
          <el-tag :type="row.mainRenter?.renterType === '1' ? 'success' : 'primary'">
            {{ row.mainRenter?.renterType === '1' ? '省内房客' : row.mainRenter?.renterType === '2' ? '省外房客' : '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mainRenter.contacts" />
      <el-table-column label="身份证号" align="center" prop="mainRenter.idCardNumber" />
      <el-table-column label="申请时间" align="center" prop="createTime" width="180" />
      <el-table-column label="房间信息" align="center">
        <template #default="{ row }">
          <span v-if="row.room && row.room.name">{{ row.room.name }} {{ row.room.buildingName ? `- ${row.room.buildingName}` : '' }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-tag :type="statusOptions.find(item => item.value === row.status)?.type || 'info'">{{ statusOptions.find(item => item.value === row.status)?.label || '未知状态' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒绝原因" align="center" prop="rejectReason" v-if="showRejectReason" />
      <el-table-column label="同住人数" align="center">
        <template #default="{ row }">
          <span v-if="row && row.renterList">{{ row.renterList.length - 1 }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="250">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-if="row.status === '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(row)"
            v-if="row.status === '0'"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-house"
            @click="handleCheckIn(row)"
            v-if="row.status === '1'"
          >办理入住</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 使用可复用的审核对话框组件 -->
    <audit-dialog
      v-model="auditOpen"
      :register-id="selectedRegisterId"
      @submit="handleAuditSubmit"
    />

    <!-- 使用可复用的办理入住对话框组件 -->
    <check-in-dialog
      v-model="checkInOpen"
      :register-id="selectedRegisterId"
      @submit="handleCheckInSubmit"
    />

    <!-- 查看详情对话框 -->
    <el-dialog title="预登记详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请人">{{ viewForm.applicantName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ viewForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ viewForm.idCard }}</el-descriptions-item>
        <el-descriptions-item label="期望入住日期">{{ viewForm.expectedCheckInDate }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ viewForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="房间信息">
          <span v-if="viewForm.room && viewForm.room.name">{{ viewForm.room.name }} {{ viewForm.room.buildingName ? `- ${viewForm.room.buildingName}` : '' }}</span>
          <span v-else>--</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.pre_register_status" :value="viewForm.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ viewForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, getInfo, save, update, remove, audit, checkIn } from "@/api/room/preregister";
import { listAvailableRooms } from "@/api/room/room";
import AuditDialog from "@/components/preregister/AuditDialog";
import CheckInDialog from "@/components/preregister/CheckInDialog";

export default {
  name: "PreRegister",
  components: {
    AuditDialog,
    CheckInDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预登记表格数据
      preregisterList: [],
      // 是否显示审核弹出层
      auditOpen: false,
      // 是否显示分配房间弹出层
      assignRoomOpen: false,
      // 是否显示办理入住弹出层
      checkInOpen: false,
      // 是否显示查看详情弹出层
      viewOpen: false,
      // 房间选项
      roomOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicantName: null,
        phone: null,
        status: null
      },
      // 审核表单参数
      auditForm: {
        id: null,
        status: "1",
        remark: null
      },
      // 分配房间表单参数
      assignRoomForm: {
        id: null,
        roomId: null,
        searchKey: ''
      },
      // 查看详情表单
      viewForm: {},
      // 审核表单校验
      auditRules: {
        status: [
          { required: true, message: "审核结果不能为空", trigger: "change" }
        ]
      },
      // 分配房间表单校验
      assignRoomRules: {
        roomId: [
          { required: true, message: "房间不能为空", trigger: "change" }
        ]
      },
      // 状态选项
      statusOptions: [
        { value: '0', label: '待审核', type: 'warning' },
        { value: '1', label: '已审核', type: 'primary' },
        { value: '2', label: '已拒绝', type: 'danger' },
        { value: '4', label: '已入住', type: 'success' }
      ],
      // 是否显示拒绝原因
      showRejectReason: false,
      // 操作加载状态
      submitLoading: false,
      // 当前选中的预登记ID
      selectedRegisterId: null
    };
  },
  created() {
    this.getList();
    // 监听查询参数变化来控制拒绝原因列的显示
    this.setRejectReasonVisible();
  },
  watch: {
    'queryParams.status': {
      handler(val) {
        this.setRejectReasonVisible();
      }
    }
  },
  methods: {
    /** 设置拒绝原因列的显示状态 */
    setRejectReasonVisible() {
      // 如果查询的是已拒绝状态，显示拒绝原因列
      this.showRejectReason = this.queryParams.status === '2';
    },
    /** 查询预登记列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        if (response.code === 200) {
          this.preregisterList = response.rows || [];
          this.total = response.total || 0;
        } else {
          this.$modal.msgError(response.msg || "获取列表失败");
          this.preregisterList = [];
          this.total = 0;
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取预登记列表失败:", error);
        this.preregisterList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/preregister/create');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row || !row.registerId) {
        this.$modal.msgError("无效的数据记录");
        return;
      }
      
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(row.registerId)
        .then(response => {
          this.loading = false;
          if (response.code === 200) {
            // 获取成功后再跳转
            this.$router.push(`/preregister/edit/${row.registerId}`);
          } else {
            this.$modal.msgError(response.msg || "获取预登记信息失败");
          }
        })
        .catch(error => {
          this.loading = false;
          console.error("获取预登记信息失败:", error);
          this.$modal.msgError("获取预登记信息失败");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.registerId || this.ids;
      this.$modal.confirm('是否确认删除预登记编号为"' + ids + '"的数据项？').then(function() {
        return remove(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      if (!row || !row.registerId) {
        this.$modal.msgError("无效的数据记录");
        return;
      }
      
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(row.registerId)
        .then(response => {
          this.loading = false;
          if (response.code === 200) {
            const latestData = response.data || {};
            // 检查状态是否已变更
            if (latestData.status !== '0') {
              this.$modal.msgWarning("当前预登记状态已发生变化，无法进行审核操作");
              // 刷新列表
              this.getList();
              return;
            }
            
            this.selectedRegisterId = row.registerId;
            this.auditOpen = true;
          } else {
            this.$modal.msgError(response.msg || "获取预登记信息失败");
          }
        })
        .catch(error => {
          this.loading = false;
          console.error("获取预登记信息失败:", error);
          this.$modal.msgError("获取预登记信息失败");
        });
    },
    /** 处理审核提交 */
    handleAuditSubmit(formData) {
      this.submitLoading = true;
      audit(formData.id, formData.status, formData.remark).then(response => {
        this.submitLoading = false;
        if (response.code === 200) {
          this.$modal.msgSuccess("审核成功");
          this.auditOpen = false;
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "审核失败");
        }
      }).catch(error => {
        this.submitLoading = false;
        console.error("审核预登记失败:", error);
        this.$modal.msgError("审核失败");
      });
    },
    /** 办理入住按钮操作 */
    handleCheckIn(row) {
      if (!row || !row.registerId) {
        this.$modal.msgError("无效的数据记录");
        return;
      }
      
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(row.registerId)
        .then(response => {
          this.loading = false;
          if (response.code === 200) {
            const latestData = response.data || {};
            // 只检查状态是否已变更，不再检查是否已分配房间
            if (latestData.status !== '1') {
              this.$modal.msgWarning("当前预登记状态已发生变化，无法办理入住操作");
              // 刷新列表
              this.getList();
              return;
            }
            
            this.selectedRegisterId = row.registerId;
            this.checkInOpen = true;
          } else {
            this.$modal.msgError(response.msg || "获取预登记信息失败");
          }
        })
        .catch(error => {
          this.loading = false;
          console.error("获取预登记信息失败:", error);
          this.$modal.msgError("获取预登记信息失败");
        });
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      if (!row || !row.registerId) {
        this.$modal.msgError("无效的数据记录");
        return;
      }
      this.$router.push(`/preregister/detail/${row.registerId}`);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.registerId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 重置表单数据 */
    reset() {
      this.form = {
        id: null,
        applicantName: null,
        phone: null,
        idCard: null,
        expectedCheckInDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 筛选房间列表 */
    filterRooms() {
      // 筛选逻辑已在计算属性中处理
      console.log("筛选房间关键词: ", this.assignRoomForm.searchKey);
    },
    /** 处理分配房间提交 */
    handleAssignRoomSubmit(formData) {
      this.submitLoading = true;
      // 调用接口，将租金租期信息作为扩展数据传递
      const params = {
        registerId: formData.id,
        roomId: formData.roomId,
        rentInfo: {
          checkInStart: formData.checkInStart,
          checkInEnd: formData.checkInEnd,
          rentCollectType: formData.rentCollectType,
          rent: formData.rent,
          deposit: formData.deposit,
          rentType: formData.rentType,
          remark: formData.remark
        }
      };
      
      assignRoom(formData.id, formData.roomId, params.rentInfo)
        .then(response => {
          this.submitLoading = false;
          if (response.code === 200) {
            this.$modal.msgSuccess("分配房间成功");
            this.assignRoomOpen = false;
            this.getList();
          } else {
            this.$modal.msgError(response.msg || "分配房间失败");
          }
        })
        .catch(error => {
          this.submitLoading = false;
          console.error("分配房间失败:", error);
          this.$modal.msgError("分配房间失败");
        });
    },
    /** 处理办理入住提交 */
    handleCheckInSubmit(formData) {
      this.submitLoading = true;
      
      checkIn(formData.id, formData.roomId, formData)
        .then(response => {
          this.submitLoading = false;
          if (response.code === 200) {
            this.$modal.msgSuccess("办理入住成功");
            this.checkInOpen = false;
            this.getList();
          } else {
            this.$modal.msgError(response.msg || "办理入住失败");
          }
        })
        .catch(error => {
          this.submitLoading = false;
          console.error("办理入住失败:", error);
          this.$modal.msgError("办理入住失败");
        });
    },
    /** 查看详情按钮操作(弹窗) */
    handleViewDetail(row) {
      if (!row || !row.registerId) {
        this.$modal.msgError("无效的数据记录");
        return;
      }
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(row.registerId).then(response => {
        this.loading = false;
        if (response.code === 200) {
          this.viewForm = response.data || {};
          this.viewOpen = true;
        } else {
          this.$modal.msgError(response.msg || "获取预登记信息失败");
        }
      }).catch(error => {
        this.loading = false;
        console.error("获取预登记信息失败:", error);
        this.$modal.msgError("获取预登记信息失败");
      });
    }
  },
  computed: {
    // 过滤后的房间列表
    filteredRoomOptions() {
      if (!this.assignRoomForm.searchKey || !this.roomOptions || this.roomOptions.length === 0) {
        return this.roomOptions;
      }
      const searchKey = this.assignRoomForm.searchKey.toLowerCase();
      return this.roomOptions.filter(room => {
        return (room.roomNumber && room.roomNumber.toLowerCase().includes(searchKey)) ||
               (room.roomName && room.roomName.toLowerCase().includes(searchKey)) ||
               (room.name && room.name.toLowerCase().includes(searchKey)) ||
               (room.buildingName && room.buildingName.toLowerCase().includes(searchKey)) ||
               (room.building && room.building.toLowerCase().includes(searchKey)) ||
               (room.typeName && room.typeName.toLowerCase().includes(searchKey)) ||
               (room.roomType && room.roomType.toLowerCase().includes(searchKey)) ||
               (room.floorName && room.floorName.toLowerCase().includes(searchKey));
      });
    }
  }
};
</script> 